package com.xbongbong.parent.help;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasListGroupEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.parent.service.ListGroupService;
import com.xbongbong.paas.model.PaasListGroupModel;
import com.xbongbong.parent.pojo.GroupConditionPoJo;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.parent.pojo.list.ConditionListPojo;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.PublicGroupEntity;
import com.xbongbong.saas.domain.entity.PublicGroupSeniorEntity;
import com.xbongbong.saas.enums.ListGroupEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.model.PublicGroupModel;
import com.xbongbong.saas.model.PublicGroupSeniorModel;
import com.xbongbong.sys.domain.entity.UserEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author haibin.zhang
 * @version v1.0
 * @date 2019/3/20 12:38
 * @since v1.0
 */
@Component
public class PublicGroupHelp {
    private static final Logger LOG = LoggerFactory.getLogger(PublicGroupHelp.class);



    @Resource
    private ListGroupService listGroupService;
    @Resource
    private PublicGroupModel publicGroupModel;
    @Resource
    private PaasListGroupModel paasListGroupModel;
    @Resource
    private ListGroupHelp listGroupHelp;
    @Resource
    private PublicGroupSeniorModel publicGroupSeniorModel;
    @Resource
    private CommonHelp commonHelp;


    /**
     * com.xbongbong.saas.help.SaasListHelp#packageGroupList(com.xbongbong.paas.pojo.dto.FormDataListDTO, java.util.List, java.util.List)
     * 封装分组条件
     * 列表、汇总、筛选、附近客户、产品、工单
     * 列表、汇总、筛选会有公海分组、且需要formId
     * @param shouldConditionList
     * @return
     * @throws XbbException
     */
    public GroupConditionPoJo packageGroupList(ConditionListPojo conditionListPojo, List<List<ConditionsEntityExt>> shouldConditionList) throws XbbException {


        List<ConditionsEntityExt> groupConditionList = new ArrayList<>();

        String corpid = conditionListPojo.getCorpid();
        Integer defaultGroup = conditionListPojo.getDefaultGroup();
        Long listGroupId = conditionListPojo.getListGroupId();
        Integer businessType = conditionListPojo.getBusinessType();
        if (listGroupId != null || Objects.equals(defaultGroup, 2)) {
            PaasListGroupEntity paasListGroupEntity;
            if (Objects.equals(defaultGroup, 1)) {
                FormDataListDTO formDataListDTO = new FormDataListDTO();
                formDataListDTO.setListGroupId(conditionListPojo.getListGroupId());
                formDataListDTO.setBusinessType(businessType);
                formDataListDTO.setUserId(conditionListPojo.getUserVO().getUserId());
                formDataListDTO.setCorpid(corpid);
                paasListGroupEntity = listGroupHelp.getDefaultGroup(formDataListDTO);
            } else if (Objects.equals(defaultGroup, 2)) {
                GroupConditionPoJo groupConditionPoJo = getPublicGroup(conditionListPojo);
                paasListGroupEntity = groupConditionPoJo.getPaasListGroupEntity();
                shouldConditionList.addAll(conditionListPojo.getShouldConditionList());
            } else {
                paasListGroupEntity = paasListGroupModel.getByKey(listGroupId, corpid);
            }
            if (paasListGroupEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.LIST_GROUP_NOT_EXIST);
            }
            List<ConditionsEntityExt> listGroupConditionList = JSONArray.parseArray(paasListGroupEntity.getJsonData(), ConditionsEntityExt.class);
            if (listGroupConditionList != null && !listGroupConditionList.isEmpty()) {
                //conditionList筛选条件
                //分组条件加入到conditionList中
                groupConditionList.addAll(listGroupConditionList);
            }
        }
        return new GroupConditionPoJo(groupConditionList, shouldConditionList);
    }

    public GroupConditionPoJo getPublicGroup(ConditionListPojo conditionListPojo) throws XbbException {

        PaasListGroupEntity paasListGroupEntity = new PaasListGroupEntity();
        String corpid = conditionListPojo.getCorpid();
        Integer businessType = conditionListPojo.getBusinessType();
        boolean isBoss = conditionListPojo.getUserVO().isAdminOrBoss();
        boolean maxDataPermission = conditionListPojo.getUserVO().isMaxDataPermission();
        boolean publicPoolSenior = Boolean.FALSE;
        String attr = null;
        if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
            publicPoolSenior = commonHelp.isCustomerPublicPoolSeniorModel(corpid);
            attr = CustomerManagementEnum.PUBLIC_GROUP.getAttr();
        } else {
            publicPoolSenior = commonHelp.isCluePublicPoolSeniorModel(corpid);
            attr = ClueEnum.PUBLIC_GROUP.getAttr();
        }
        List<List<ConditionsEntityExt>> publicGroupConditions = conditionListPojo.getShouldConditionList();

        if (publicPoolSenior) {
            boolean isAll = Objects.isNull(conditionListPojo.getListGroupId()) || (conditionListPojo.getDefaultGroup() == 2 && ListGroupEnum.ALL.getCode().equals(conditionListPojo.getListGroupId().intValue()));
            UserEntity userEntity = new UserEntity();
            BeanUtil.copyProperties(conditionListPojo.getUserVO(),userEntity);
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid",corpid);
            param.put("formId",conditionListPojo.getFormId());
            param.put("status", BasicConstant.ONE);
            param.put("orderByStr","sort asc");
            List<PublicGroupSeniorEntity> publicGroupSeniorEntityList = publicGroupSeniorModel.findEntitys(param);
            //权限过滤处理
            //List<PublicGroupSeniorEntity> newPublicGroupSeniorEntityList = new ArrayList<>();
            if (!isBoss && !maxDataPermission) {
                publicGroupSeniorEntityList = publicGroupSeniorModel.filterGroupSeniorByUser(publicGroupSeniorEntityList, userEntity);
            }
            if (isAll) {
                if (!isBoss && !maxDataPermission){
                    if (CollectionsUtil.isNotEmpty(publicGroupSeniorEntityList)) {
                        //过滤分组ID
                        List<Object> groupIdList = publicGroupSeniorEntityList.stream().map(PublicGroupSeniorEntity::getId).collect(Collectors.toList());
                        if (CollectionsUtil.isNotEmpty(groupIdList)) {
                            List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>();
                            //直接封装分组条件
                            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
                            conditionsEntityExt.setAttr(attr);
                            conditionsEntityExt.setFieldType(FieldTypeEnum.PUBLIC_GROUP.getType());
                            conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
                            conditionsEntityExt.setValue(groupIdList);
                            conditionsEntityExtList.add(conditionsEntityExt);
                            publicGroupConditions.add(conditionsEntityExtList);
                        }
                        //找出无分组
                        PublicGroupSeniorEntity publicGroupSeniorEntity = publicGroupSeniorEntityList.stream().filter(item -> Objects.equals(item.getGroupType(),BasicConstant.TWO) && Objects.equals(item.getDel(),BasicConstant.ZERO)).findAny().orElse(null);
                        if (Objects.nonNull(publicGroupSeniorEntity)) {
                            List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>();
                            //直接封装分组条件
                            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
                            conditionsEntityExt.setAttr(attr);
                            conditionsEntityExt.setFieldType(FieldTypeEnum.PUBLIC_GROUP.getType());
                            conditionsEntityExt.setSymbol(ConditionEnum.EMPTY.getSymbol());
                            conditionsEntityExtList.add(conditionsEntityExt);
                            publicGroupConditions.add(conditionsEntityExtList);
                        }

                    } else {
                        publicGroupConditions.add(Collections.singletonList(new ConditionsEntityExt(FieldTypeEnum.DATAID.getAlias(),"",FieldTypeEnum.DATAID.getType(),ConditionEnum.IN.getSymbol(),Collections.singletonList(-1L))));
                    }
                }
            } else if (Objects.equals(conditionListPojo.getListGroupId(), ListGroupEnum.APPROVAL.getCode().longValue())) {
                // 审批中列表不处理
                return new GroupConditionPoJo(publicGroupConditions, new PaasListGroupEntity());
            } else {
                PublicGroupSeniorEntity publicGroupSeniorEntity = publicGroupSeniorModel.getByKey(conditionListPojo.getListGroupId(), corpid);
                if (Objects.nonNull(publicGroupSeniorEntity) && Objects.equals(publicGroupSeniorEntity.getStatus(),BasicConstant.ONE)) {
                    List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>();
                    //直接封装分组条件
                    ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(attr);
                    conditionsEntityExt.setFieldType(FieldTypeEnum.PUBLIC_GROUP.getType());
                    if (!Objects.equals(publicGroupSeniorEntity.getGroupType(),BasicConstant.TWO)) {
                        conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
                        conditionsEntityExt.setValue(Arrays.asList(publicGroupSeniorEntity.getId()));
                    } else {
                        conditionsEntityExt.setSymbol(ConditionEnum.EMPTY.getSymbol());
                        //还需要去查已经删除的分组
                        publicGroupSeniorEntityList.removeIf(item -> Objects.equals(item.getDel(), BasicConstant.ZERO));
                        List<Object> delGroupIdList = publicGroupSeniorEntityList.stream().map(PublicGroupSeniorEntity::getId).collect(Collectors.toList());
                        if (CollectionsUtil.isNotEmpty(delGroupIdList)) {
                            List<ConditionsEntityExt> delGroupConditions = new ArrayList<>();
                            ConditionsEntityExt delGroupCondition = new ConditionsEntityExt();
                            delGroupCondition.setAttr(attr);
                            delGroupCondition.setFieldType(FieldTypeEnum.PUBLIC_GROUP.getType());
                            delGroupCondition.setSymbol(ConditionEnum.IN.getSymbol());
                            delGroupCondition.setValue(delGroupIdList);
                            delGroupConditions.add(delGroupCondition);
                            publicGroupConditions.add(delGroupConditions);
                        }
                    }
                    conditionsEntityExtList.add(conditionsEntityExt);
                    publicGroupConditions.add(conditionsEntityExtList);
                }
            }
        } else {
            //公海池分组
            boolean isAll = Objects.isNull(conditionListPojo.getListGroupId()) || (conditionListPojo.getDefaultGroup() == 2 && ListGroupEnum.ALL.getCode().equals(conditionListPojo.getListGroupId().intValue()));
            if (isAll){
                if (!isBoss && !maxDataPermission){
                    UserEntity userEntity = new UserEntity();
                    BeanUtil.copyProperties(conditionListPojo.getUserVO(),userEntity);
                    List<PublicGroupEntity> publicGroupEntityList = publicGroupModel.enableListByFormId(corpid, conditionListPojo.getFormId());
                    if (publicGroupEntityList.isEmpty()){
                        // 没有分组权限，那么就不给数据
                        return new GroupConditionPoJo(publicGroupConditions, paasListGroupEntity);
                    }
                    List<PublicGroupEntity> newPublicGroupList = listGroupService.filterGroupByUser(publicGroupEntityList,userEntity);
                    for (PublicGroupEntity entity : newPublicGroupList){
                        List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>();
                        JSONArray jsonArray = entity.getJsonData();
                        for (Object obj : jsonArray){
                            JSONObject json = (JSONObject) obj;
                            ConditionsEntityExt conditionsEntityExt = JSONObject.parseObject(json.toJSONString(),ConditionsEntityExt.class);
                            // 负责人转为前负责人
                            if (Objects.equals(conditionsEntityExt.getAttr(), FieldTypeEnum.OWNERID.getAlias())) {
                                conditionsEntityExt.setAttr(FieldTypeEnum.PRE_OWNER_ID.getAlias());
                                conditionsEntityExt.setFieldType(FieldTypeEnum.PRE_OWNER_ID.getType());
                            }
                            conditionsEntityExtList.add(conditionsEntityExt);
                        }
                        publicGroupConditions.add(conditionsEntityExtList);
                    }
                    if (publicGroupConditions.isEmpty()){
                        publicGroupConditions.add(Collections.singletonList(new ConditionsEntityExt(FieldTypeEnum.DATAID.getAlias(),"",FieldTypeEnum.DATAID.getType(),ConditionEnum.IN.getSymbol(),Collections.singletonList(-1L))));
                    }
                }
            } else if (Objects.equals(conditionListPojo.getListGroupId(), ListGroupEnum.APPROVAL.getCode().longValue())) {
                // 审批中列表不处理
                return new GroupConditionPoJo(publicGroupConditions, new PaasListGroupEntity());
            } else {
                PublicGroupEntity publicGroupEntity = publicGroupModel.getByKey(conditionListPojo.getListGroupId(), corpid);
                if (publicGroupEntity == null) {
                    // 没有分组权限，那么就不给数据
                    ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt(FieldTypeEnum.DATAID.getAlias(),"",FieldTypeEnum.DATAID.getType(),ConditionEnum.EQUAL.getSymbol(),Collections.singletonList(-1));
                    paasListGroupEntity.setJsonData(JSONArray.toJSONString(Collections.singleton(conditionsEntityExt)));
                    return new GroupConditionPoJo(publicGroupConditions, paasListGroupEntity);
                }
                JSONArray jsonArray = publicGroupEntity.getJsonData();
                List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>();
                for (Object obj : jsonArray){
                    JSONObject json = (JSONObject) obj;
                    ConditionsEntityExt conditionsEntityExt = JSONObject.parseObject(json.toJSONString(),ConditionsEntityExt.class);
                    // 负责人转为前负责人
                    if (Objects.equals(conditionsEntityExt.getAttr(), FieldTypeEnum.OWNERID.getAlias())) {
                        conditionsEntityExt.setAttr(FieldTypeEnum.PRE_OWNER_ID.getAlias());
                        conditionsEntityExt.setFieldType(FieldTypeEnum.PRE_OWNER_ID.getType());
                    }
                    conditionsEntityExtList.add(conditionsEntityExt);
                }
                paasListGroupEntity.setJsonData(JSONArray.toJSONString(conditionsEntityExtList));
            }
        }
        return new GroupConditionPoJo(publicGroupConditions, paasListGroupEntity);
    }
}
